import json
from urllib.parse import urlencode,parse_qs
import logging
from urllib.request import urlopen

from itsdangerous import BadData
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings

from oauth import constants
from oauth.exceptions import QQAPIError

logger = logging.getLogger('django')

class OAuthQQ(object):
    """QQ辅助工具"""
    def __init__(self,client_id=None,redirect_uri=None,state=None,client_sectret=None):
        self.client_id = client_id or settings.QQ_CLIENT_ID
        self.redirect_uri = redirect_uri or settings.QQ_REDIRECT_URI
        self.state = state or settings.QQ_STATE
        # self.state = state if state else settigs.QQ_STATE
        self.client_secret = client_sectret or settings.QQ_CLIENT_SECRET


    def get_qq_login_url(self,state):
        url = 'https://graph.qq.com/oauth2.0/authorize?'
        params = {
            'response_type': 'code',
            'client_id': self.client_id,
            'redirect_uri': self.redirect_uri,
            'state': self.state,
            'scope': 'get_user_info',
        }
        url += urlencode(params)
        return url

    def get_access_token(self,code):
        """
                获取access_token
                :param code: qq提供的code
                :return: access_token
                """
        params = {
            'grant_type': 'authorization_code',
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'code': code,
            'redirect_uri': self.redirect_uri
        }
        url = 'https://graph.qq.com/oauth2.0/token?' + urlencode(params)
        response = urlopen(url)
        response_data = response.read().decode()
        print(response_data)
        data = parse_qs(response_data)
        print(data)
        access_token = data.get('access_token',None)
        if not access_token:
            logger.error('code=%s msg=%s' % (data.get('code'), data.get('msg')))
            raise QQAPIError
        return access_token[0]

    def get_openid(self,access_token):

        url = 'https://graph.qq.com/oauth2.0/me?access_token=' + access_token

        response = urlopen(url)
        response_data = response.read().decode()
        try:
            data = json.loads(response_data[10:-4])
            print(data)
        except Exception:
            data = parse_qs(response_data)
            logger.error('code=%s msg=%s' % (data.get('code'), data.get('msg')))
            raise QQAPIError
        else:
            openid = data.get('openid')
            return openid

    @staticmethod
    def generate_save_user_token(openid):
        """
        生成保存用户数据的token
        :param openid: 用户的openid
        :return: token
        """
        serializer = Serializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
        data = {'openid': openid}
        token = serializer.dumps(data)
        return token.decode()

    @staticmethod
    def check_save_user_token(token):
        """
        检验保存用户数据的token
        :param token: token
        :return: openid or None
        """
        serializer = Serializer(settings.SECRET_KEY, expires_in=constants.SAVE_QQ_USER_TOKEN_EXPIRES)
        try:
            data = serializer.loads(token)
        except BadData:
            return None
        else:
            return data.get('openid')




